package com.yutian.springboot.jdbctemplate.biz;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zhoulei7
 * @create 2020-09-28
 **/
@Deprecated
@Component
public class StudentDataSourceBiz {

    @Autowired
    private DataSource dataSource;

    public List<Map<String, Object>> get(Long id) {
        List<Map<String, Object>> res = query("SELECT id, `first`, `last`, age FROM testyt.student where id = ?", new Object[]{id});
        return res;
    }

    /*
     *
     * 建立连接
     * */
    private Connection getConnection() {
        try {
            return dataSource.getConnection();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    private void close(ResultSet rs, Statement stm, Connection con) {

        try {
            if (rs != null) {
                rs.close();
            }

            if (stm != null) {
                stm.close();
            }

            if (con != null) {
                con.close();
            }
        } catch (Exception e) {
            // 吃掉
            e.printStackTrace();
        }
    }

    /**
     * 方法executeQuery
     * 用于产生单个结果集（ResultSet）的语句，例如:被执行最多的SELECT 语句。
     * 这个方法被用来执行 SELECT 语句，但也只能执行查询语句，执行后返回代表查询结果的ResultSet对象。
     *
     *
     * @param preparedStatementSql
     */
    public List<Map<String, Object>> query(String preparedStatementSql, Object[] params) {
        Connection con = getConnection();

        PreparedStatement pres = null;
        ResultSet rs = null;
        try {
            pres = con.prepareStatement(preparedStatementSql);
            // 使用setObject可以自动识别SQL中的数据类型
            for(int i=0;i<params.length;i++) {
                // 从1开始
                pres.setObject(i+1, params[i]);
            }
            rs = pres.executeQuery();
            return printResultSet(rs);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            close(rs, pres, con);
        }
    }

    private static List<Map<String, Object>> printResultSet(ResultSet rs) throws SQLException {
        List<Map<String, Object>> res = new ArrayList<>();
        StringBuilder sb = new StringBuilder("结果为：\r\n");
        //获取结果集
        ResultSetMetaData rsmd = rs.getMetaData();
        //ResultSetMetaData是用于分析结果集的元数据接口
        int  columnCount = rsmd.getColumnCount();
        while (rs.next()){//输出ResultSet对象
            // LinkedHashMap保持顺序！
            Map<String, Object> row = new HashMap<>();
            // 标题
            for (int i = 0 ; i < columnCount ; i++ ) {
                sb.append(rsmd.getColumnLabel(i+1) + "     |     ");
            }
            sb.append("\r\n-----------------------------------------------------\r\n");
            // 内容
            for (int i = 0 ; i < columnCount ; i++ ) {
                sb.append(rs.getString(i + 1) + "     |     ");
                row.put(rsmd.getColumnLabel(i+1), rs.getString(i + 1));
            }
            sb.append("\r\n");
            res.add(row);
        }
        System.out.println(sb.toString());
        return res;
    }
}
